package com.deepcode.StringProcess.template.impl;


import com.deepcode.StringProcess.domain.CharObject;
import com.deepcode.StringProcess.strategy.CharacterReplacementStrategy;
import com.deepcode.StringProcess.struct.CharLinkedList;
import com.deepcode.StringProcess.template.AbstractStringProcessor;

public class ApplyStrategyProcessor extends AbstractStringProcessor {

    public ApplyStrategyProcessor(CharacterReplacementStrategy strategy) {
        super(strategy);
    }

    /**
     * 处理链表中的连续字符
     * @param linkedList 双向链表
     * @return 是否有变化
     */
    @Override
    public boolean processLinkedList(CharLinkedList linkedList) {
        boolean changed = false;
        CharObject current = linkedList.getHead();

        while (current != null) {
            // 计算从当前节点开始的连续相同字符数量
            char targetChar = current.getCharacter();
            int count = 1;
            CharObject endNode = current;
            
            // 统计连续相同字符
            CharObject next = current.getNext();
            while (next != null && next.getCharacter() == targetChar) {
                count++;
                endNode = next;
                next = next.getNext();
            }
            
            // 如果连续字符数量>=3且可以替换
            if (count >= 3 && strategy.canReplace(targetChar)) {
                // 应用替换策略
                char replacement = strategy.replace(current, count);
                
                if (replacement == '\0') {
                    // 删除所有连续字符节点
                    CharObject nodeToDelete = current;
                    for (int i = 0; i < count && nodeToDelete != null; i++) {
                        CharObject nextToDelete = nodeToDelete.getNext();
                        linkedList.remove(nodeToDelete);
                        nodeToDelete = nextToDelete;
                    }
                } else {
                    // 用替换字符替换所有连续字符节点
                    // 先删除多余的节点，只保留一个
                    CharObject nodeToDelete = current.getNext();
                    for (int i = 1; i < count && nodeToDelete != null; i++) {
                        CharObject nextToDelete = nodeToDelete.getNext();
                        linkedList.remove(nodeToDelete);
                        nodeToDelete = nextToDelete;
                    }
                    // 修改保留节点的字符
                    current.setCharacter(replacement);
                }
                
                changed = true;
                current = next; // 移动到下一个不同的字符
            } else {
                current = next; // 移动到下一个不同的字符
            }
        }
        
        return changed;
    }
}